import { createSlice } from "@reduxjs/toolkit";
import { getUser,getUserInfo } from "@/apis/user";
import {getItem,setItem,removeItem} from "@/utils/localStorage"
import {TOKEN_KEY,USER_INFO} from "@/constants/index";
const tokenStore = createSlice({
     name: "user",
     initialState: {
           token:getItem(TOKEN_KEY) || '',
           userInfo:getItem(USER_INFO)||{}       
        },
     reducers: {
          setToken(state, action) {
               state.token = action.payload;
               //本地存储
               setItem(TOKEN_KEY, action.payload);
          },
          setUserInfo(state, action) {
               state.userInfo = action.payload;
               setItem(USER_INFO, action.payload);     
          },
          clearUserInfo(state, action) {
               state.token = '';
               state.userInfo = {};
               removeItem(TOKEN_KEY)
               removeItem(USER_INFO)
          },
     }
})

const fetchLogin = (logonForm)=>{
     return async(dispatch)=>{
       const res =await getUser(logonForm)
       dispatch(setToken(res.data.token))
     }
}
const fetchUserInfo = ()=>{
     return async(dispatch)=>{
          const res = await getUserInfo()
          dispatch(setUserInfo(res.data))
   }
}
const { setToken,setUserInfo,clearUserInfo } = tokenStore.actions;

export {setToken,clearUserInfo,fetchLogin,fetchUserInfo}
export default tokenStore.reducer;